package service

import (
	"errors"
	"git.oschina.net/fanbuchi/redpack/database"
	"git.oschina.net/fanbuchi/redpack/domain"
)

type WalletService struct {

}


func  (service*WalletService)Create(params *domain.Wallet)(*domain.Wallet,error)  {
	var result domain.Wallet
	database.Master().Where(&domain.Wallet{AccountId:params.AccountId}).First(&result)
	if result.ID>0 {
		 return nil,errors.New("钱包已创建")
	}
	err:=database.Master().Create(params).Error
	if err!=nil {
		return nil,err
	}
	return params,nil
}


func  (service*WalletService)Delete(params *domain.Wallet)(*domain.Wallet,error)  {
	if err:=database.Master().Delete(params).Error;err!=nil {
		return nil,err
	}
	return params,nil
}


func  (service*WalletService)Update(params *domain.Wallet)(interface{},error)  {
	var result domain.Wallet
	database.Master().Where(&domain.Wallet{AccountId:params.AccountId}).First(&result)
	if result.ID<=0 {
		database.Master().Create(params)
	}else{
		params.ID=result.ID
		if err:=database.Master().Model(params).Update(params).Error;err!=nil {
			return nil,err
		}
	}
	return params,nil
}


func  (service*WalletService)QueryById(params *domain.Wallet)(*domain.Wallet, error)  {
	var result domain.Wallet
	err:=database.Master().Where(params).First(&result).Error
	if err!=nil {
		return nil,err
	}
	return &result,nil
}



func  (service*WalletService)QueryByParam(params *domain.Wallet)(*domain.Wallet,error)  {
	err:=database.Master().Find(params).Error
	if err!=nil {
		return nil,err
	}
	return params,nil
}


func  (service*WalletService)Search(params *domain.Wallet,page int,size int)([]*domain.Wallet,error)  {
	list := make([]*domain.Wallet, 0)
	err := database.Master().
	Where(params).
	Limit(size).
	Offset((page-1)*size).
	Find(&list).
	Error
	return list,err
}
